<?php

namespace app\install\service\install\observer;

use app\common\util\base\BaseObserver;
use app\common\util\base\BaseServer;
use Matomo\Ini\IniReader;
use Matomo\Ini\IniWriter;

class WriteEnvObserver extends BaseObserver
{
    public function handle(BaseServer $server = null)
    {
        $data = $server->getInputData();
        $reader = new IniReader();
        $string = file_get_contents(root_path().'.example.env');        #加载env模板文件
        $array = $reader->readString($string);
        $db = &$array['database'];
        foreach ($db as $key => &$value){
            if (isset($data[$key])) {
                $db[$key] = $data[$key];
            }
        }
        $singleEnv = [];                                //独立的环境配置
        $groupEnv = [];                                 //分组的环境配置
        unset($value);
        foreach ($array as $key => $value) {
            if (!is_array($value)) {
                $singleEnv[$key] = $value;
            }else{
                $groupEnv[$key] = $value;
            }
        }
        $write = new IniWriter();
        $dbString = $write->writeToString($groupEnv);       //写入配置
        foreach ($singleEnv as $key=>$value) {
            $dbString = $key . '='. $value."\n\r".$dbString;
        }
        $res = file_put_contents(root_path().'.env', $dbString);
        return $res;
    }
}